package dao

import (
	"time"

	"github.com/jinzhu/gorm"
)

const (
	TableApedgeServiceNode string = "t_apedge_service_node"
)

// 服务和节点对应关系表
type ApedgeServiceNode struct {
	ID            int64      `gorm:"primary_key" json:"id"`
	OrgId         int64      `gorm:"not null" json:"orgId"`
	GroupId       int64      `gorm:"not null" json:"groupId"`
	UserId        int64      `gorm:"not null" json:"userId"`
	UserName      string     `gorm:"not null" json:"userName"`
	ServiceNodeId string     `gorm:"unique;not null" json:"serviceNodeId"`
	NodeId        string     `gorm:"not null;describe:'节点名字'" json:"nodeId"`
	ServiceId     string     `gorm:"not null;describe:'节点名字'" json:"serviceId"`
	Status        string     `gorm:"not null;describe:'状态'" json:"status"`
	CreatedAt     *time.Time `gorm:"not null" json:"createdAt"`
	UpdatedAt     *time.Time `gorm:"not null" json:"updatedAt"`
	DeletedAt     *time.Time `gorm:"default null" json:"deletedAt"`
}

func (ApedgeServiceNode) TableName() string {
	return TableApedgeServiceNode
}

func (t *ApedgeServiceNode) Save(tx *gorm.DB) error {
	return tx.Save(t).Error
}

func (t *ApedgeServiceNode) GetListByServiceId(tx *gorm.DB) ([]ApedgeServiceNode, error) {
	var items []ApedgeServiceNode

	err := tx.Where("service_id = ?", t.ServiceId).Find(&items).Error
	if err != nil {
		return nil, err
	}
	return items, err
}

func (t *ApedgeServiceNode) GetListByNodeId(tx *gorm.DB) ([]ApedgeServiceNode, error) {
	var items []ApedgeServiceNode

	err := tx.Where("node_id = ?", t.NodeId).Find(&items).Error
	if err != nil {
		return nil, err
	}
	return items, err
}

func (t *ApedgeServiceNode) GetByServiceNodeId(tx *gorm.DB) (*ApedgeServiceNode, error) {
	var item ApedgeServiceNode

	err := tx.Where("service_node_id = ?", t.ServiceNodeId).Find(&item).Error
	if err != nil {
		return nil, err
	}
	return &item, err
}

func (t *ApedgeServiceNode) DeleteByServiceNodeId(tx *gorm.DB) error {
	return tx.Where("service_node_id = ?", t.ServiceNodeId).Unscoped().Delete(&ApedgeServiceNode{}).Error
}

func (t *ApedgeServiceNode) UpdateByServiceNodeId(tx *gorm.DB, data interface{}) error {

	err := tx.Model(&ApedgeServiceNode{}).Where("service_node_id = ?", t.ServiceNodeId).Updates(data).Error

	if err != nil {
		return err
	}
	return nil
}

func (t *ApedgeServiceNode) GetListByNodeIdAndServiceId(tx *gorm.DB) ([]ApedgeServiceNode, error) {
	var items []ApedgeServiceNode

	err := tx.Where("service_id = ? AND node_id = ?", t.ServiceId, t.NodeId).Find(&items).Error
	if err != nil {
		return nil, err
	}
	return items, err
}

func (t *ApedgeServiceNode) GetListByNodeIds(tx *gorm.DB, nodeIds []string) ([]ApedgeServiceNode, error) {
	var items []ApedgeServiceNode

	err := tx.Where("node_id IN (?)", nodeIds).Find(&items).Error
	if err != nil {
		return nil, err
	}
	return items, err
}